package data

import (
	"errors"
	"sieve_admin_server_userpass/pkg/im3/db"
)

type DeptData struct {
	Did    int
	Name   string
	Leader int
	Order  int
}

func GetDeptList() ([]*DeptData, error) {
	rows, err := db.Mysql().Query("SELECT `Did`,`Name`,`Leader`,`Order` FROM `Dept` ORDER BY `Order` DESC,`Did`")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	list := []*DeptData{}
	for rows.Next() {
		m := &DeptData{}
		if err := rows.Scan(
			&m.Did,
			&m.Name,
			&m.Leader,
			&m.Order,
		); err != nil {
			return nil, err
		}
		list = append(list, m)
	}

	return list, nil
}

func GetDeptById(did int) (*DeptData, error) {
	data := &DeptData{Did: did}
	err := db.Mysql().QueryRow("SELECT `Name`,`Leader`,`Order` FROM `Dept` WHERE `Did`=?", did).Scan(&data.Name, &data.Leader, &data.Order)
	return data, err
}

func GetDeptLeader(did int) (int, error) {
	leader := 0
	err := db.Mysql().QueryRow("SELECT `Leader` FROM `Dept` WHERE `Did`=?", did).Scan(&leader)
	if err == nil && leader == 0 {
		err = errors.New("no leader in dept")
	}
	return leader, err
}

func GetDeptTreeCntList() map[int]int {
	deptMap := make(map[int]int)
	rows, err := db.Mysql().Query("SELECT `Did`,count(Uid) FROM `DeptUser` group by Did")
	if err != nil {
		return deptMap
	}
	defer rows.Close()
	for rows.Next() {
		var (
			did int
			cnt int
		)
		err := rows.Scan(&did, &cnt)
		if err != nil {
			break
		}
		deptMap[did] = cnt
	}
	return deptMap
}

func GetDeptCntList() map[int]int {
	deptMap := make(map[int]int)
	rows, err := db.Mysql().Query("SELECT `Dept`,count(Uid) FROM `User` where Dept>0 group by Dept")
	if err != nil {
		return deptMap
	}
	defer rows.Close()
	for rows.Next() {
		var (
			did int
			cnt int
		)
		err := rows.Scan(&did, &cnt)
		if err != nil {
			break
		}
		deptMap[did] = cnt
	}
	return deptMap
}
